import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import DefaultLayout from '@/components/layouts/DefaultLayout.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: DefaultLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/User.vue')
      }
    ]
  },
  // 登录页面不需要布局·
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole') // 从存储中获取用户角色
  
  if (to.meta.requiresAuth) {
    if (!userRole) {
      next({ name: 'Login' })
    } else if (to.meta.roles && Array.isArray(to.meta.roles)) {
      // 检查用户是否有权限访问该路由
      if (to.meta.roles.includes(Number(userRole))) {
        next()
      } else {
        alert('没有权限访问该页面')
        next(from.path)
      }
    }
  } else {
    next()
  }
})

export default router 